package exttable.testselector;

import dbutils.DbUtils;
import dbutils.StoredQueries;
import exttable.testfiller.InputFormDisplay;
import exttable.usingTableModelWithFindCell.JButtonTableCellRenderer;
import exttable.usingTableModelWithFindCell.UsingTableModelWithFindCell;
import exttable.view.ViewAnalysis;
import utils.Localisation;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: Jan 28, 2010
 * Time: 10:47:03 AM
 * To change this template use File | Settings | File Templates.
 */
public class ViewTestResults {

    private Vector<Vector<Object>> rowData = new Vector<Vector<Object>>();
    private Vector<String> columns = new Vector<String>();
    private Map<String, ViewAnalysis> mapColumns = new HashMap<String, ViewAnalysis>();
    private JButton edit;

    public ViewTestResults(ViewAnalysis analysis, int probId, int groupSchId, int visit) throws Exception {
        initMapColumns(analysis);
        intTableValues(analysis.getAnalysisName(), getTestId(probId, groupSchId, visit));
        columns.add(Localisation.getMessage("form.analysparam"));
        columns.add(Localisation.getMessage("form.analysvalue"));
        edit = new JButton("edit");
        editController(analysis, probId, groupSchId, visit);
        createGUI();
    }

    private void editController(final ViewAnalysis analysis, final int probId, final int groupSchId, final int visit) {
        edit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    new InputFormDisplay(analysis, probId, groupSchId, visit, rowData);

                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        });

    }

    private void initMapColumns(ViewAnalysis analysis) throws Exception {
        Connection c = DbUtils.getDBConnectionGeneral();
        PreparedStatement ps = c.prepareStatement(StoredQueries.getQuery(StoredQueries.VIEW_ANALYS_RESULT));
        try {
            ps.setInt(1, analysis.getAnalysisId());
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                ViewAnalysis va = new ViewAnalysis.Build()
                        .nameRu(rs.getString("name_ru"))
                        .nameEn(rs.getString("name_en"))
                        .nameKz(rs.getString("name_kk"))
                        .analysName(rs.getString("analys_param"))
                        .build();
                mapColumns.put(rs.getString("analys_param"), va);
            }
            ps.close();
            c.close();
        }
        catch (SQLException e) {
            throw e;
        }
        finally {
            ps.close();
            c.close();
        }
    }


    private void createGUI() {
        JFrame f = new JFrame(Localisation.getMessage("title.analysresult")+" "+DbUtils.ModeOfOperation);
        f.setLayout(new BorderLayout());
//        f.add(new JScrollPane(new JTable(rowData, columns)), BorderLayout.CENTER);
        UsingTableModelWithFindCell usingTableModelWithFindCell=new UsingTableModelWithFindCell(false);
        usingTableModelWithFindCell.setDataSource(rowData, columns);
        JTable jTable=new JTable(usingTableModelWithFindCell);
        JButtonTableCellRenderer jButtonTableCellRenderer=new JButtonTableCellRenderer();
        jButtonTableCellRenderer.setCellCoordinate(usingTableModelWithFindCell.getCellCoordinateForTwoColumnsTable("снимок"));
        jButtonTableCellRenderer.setOpenFileMouseClicked(jTable);
        jTable.setDefaultRenderer(Object.class, jButtonTableCellRenderer);
        f.add(new JScrollPane(jTable), BorderLayout.CENTER);
        f.add(edit, BorderLayout.SOUTH);
        f.pack();
        f.setVisible(true);
    }

    private void intTableValues(String tableName, int testId) throws Exception {
        Connection c = DbUtils.getDBConnectionGeneral();

        PreparedStatement ps;
        ps = c.prepareStatement("select COLUMN_NAME from information_SCHEMA.COLUMNS t2  where TABLE_NAME = ? and TABLE_SCHEMA = '" + DbUtils.GENERAL_DATABASE_NAME + "'");
        try {
            ps.setString(1, tableName);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Vector<Object> row = new Vector<Object>();
                ps = c.prepareStatement("select " + rs.getString(1) + " from " + tableName + " where test_id = ?");
                ps.setInt(1, testId);
                ResultSet rsRow = ps.executeQuery();
                while (rsRow.next()) {
                    row.add(mapColumns.get(rs.getString(1)));
                    row.add(rsRow.getString(1));
                }
                rowData.add(row);
            }
            c.close();
        }
        catch (SQLException e) {
            e.printStackTrace();

        } finally {
            ps.close();
            c.close();
        }
    }

    private int getTestId(int probId, int groupSchId, int visit) throws Exception {
        Integer toReturn = null;
        Connection c = DbUtils.getDBConnectionGeneral();

        PreparedStatement ps = c.prepareStatement("select vd.test_id from visit_details vd where " +
                "   vd.probationer_id = ? " +
                "   and vd.visit_id = ?" +
                "   and vd.groups_schema_visits_id = ?");

        try {
            ps.setInt(1, probId);
            ps.setInt(2, visit);
            ps.setInt(3, groupSchId);
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                toReturn = rs.getInt(1);
            }
            c.close();
            return toReturn;
        }
        catch (SQLException e) {
            throw new SQLException("db error");
        }
        finally {
            ps.close();
            c.close();
        }
    }


}
